package com.zoe.onelink.feign.util;

import com.zoe.onelink.common.constant.TraceSpanConstant;
import com.zoe.onelink.common.exception.InnerApiException;
import com.zoe.onelink.common.model.ApiResult;
import com.zoe.onelink.util.IpUtil;
import com.zoe.onelink.util.OnelinkContextHolder;
import com.zoe.onelink.util.StrUtil;
import feign.Request;
import feign.Response;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-08-23
 */
public class FeignDecoderUtil {

    public static InnerApiException createInnerApiEx(Response response, ApiResult<?> apiResult) {
        Request request = response.request();
        String message = StrUtil.nullToDefault(apiResult.getMessage(), "Feign invoke failure.");
        String feignTargetUrl = OnelinkContextHolder.getString(TraceSpanConstant.RPC_REMOTE_ADDR);
        String feignInvokeIp = IpUtil.parseIpAndPort(feignTargetUrl);
        String error = StrUtil.format("Feign [{}] [{}] to [{}] [{}] failure .\n{}",
                response.status(), request.httpMethod().name(), feignInvokeIp, request.url(), apiResult.getError());
        return new InnerApiException(apiResult.getCode(), message, error)
                // 返回状态码如果是200说明是业务异常
                .setBizException(response.status() == 200);
    }

}
